﻿using IntoStationSystem.Db;
using IntoStationSystem.Entity;
using IntoStationSystem.Global;
using IntoStationSystem.Models;
using IntoStationSystem.ViewModels;
using IntoTheme.Controls;
using LiveCharts;
using LiveCharts.Wpf;
using S7.Net;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using static IntoStationSystem.Global.Events;

namespace IntoStationSystem.Views
{
    /// <summary>
    /// MainPage.xaml 的交互逻辑
    /// </summary>
    public partial class HomeView : UserControl
    {
        HomeViewModel vm => Locator.Instance.MainPageVM;
        MainWindowViewModel mwvm => Locator.Instance.MainWindowVM;
        public SeriesCollection PieCollection { get; set; } = new SeriesCollection()
        {
            new PieSeries() { DataLabels = true,Title = "合格",  Values = new ChartValues<double>{ 30} },
            new PieSeries() { DataLabels = true,Title = "不合格",Values = new ChartValues<double>{ 70} },
        };
        public HomeView()
        {
            InitializeComponent();
            this.DataContext = vm;
            timer.Tick += PipeShowTick;
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Start();
            RstCodeBtn = rstCodeBtn;
            this.Dispatcher.Invoke(new Action(delegate
            {
                //要做的事
                vm.QualityBtn = qualityBtn;
            }));

            //vm.QualityBtn = qualityBtn;

            //vm.PhotoUrl1 = Fields.Photo;
            //添加图片布局
            if (Fields.Station == "JZ" || Fields.Station == "GP12")
            {
                ColumnDefinition newColumn = new ColumnDefinition();
                imgGrid.ColumnDefinitions.Insert(0, newColumn);
                vm.PhotoUrl2 = Fields.Photo;
                vm.PhotoUrl1 = Fields.Photo;
            }
            else
            {
                vm.PhotoUrl2 = Fields.Photo;
            }

            if (Fields.Station != "OP10")
            {
                emptyTrayBtn.Visibility = Visibility.Collapsed;
            }
            else
            {
                ColumnDefinition newColumn = new ColumnDefinition();
                imgGrid.ColumnDefinitions.Insert(0, newColumn);
                imgGrid.ColumnDefinitions[0].Width = new GridLength(200);
                TightenGrid.Visibility = Visibility.Visible;

            }
            if (Fields.Station != "OP50")
            {
                retestBtn.Visibility = Visibility.Collapsed;
                emptyTrayBtn.SetValue(Grid.RowProperty, 4);
                emptyTrayBtn.SetValue(Grid.ColumnProperty, 1);
            }
            else
            {
                ColumnDefinition newColumn = new ColumnDefinition();
                imgGrid.ColumnDefinitions.Insert(0, newColumn);
                imgGrid.ColumnDefinitions[0].Width = new GridLength(260);
                FanPanel.Visibility = Visibility.Visible;
            }







        }
        DispatcherTimer timer = new DispatcherTimer();
        DispatcherTimer timer1 = new DispatcherTimer();
        public static ScriptBtn RstCodeBtn = new ScriptBtn();
        int total = -1;
        double okPercent = 0;
        double ngPercent = 0;
        private DateTime startUpTime = DateTime.Now;
        /// <summary>
        /// 饼图
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void PipeShowTick(object obj, EventArgs e)
        {
            if (total != vm.HomeModel.ProduceCount)
            {
                total = vm.HomeModel.ProduceCount;
                if (total == 0)
                {
                    okPercent = 100;
                    ngPercent = 0;
                }
                else
                {
                    okPercent = Math.Round(vm.HomeModel.OKCount / (double)vm.HomeModel.ProduceCount * 100, 2);
                    ngPercent = Math.Round(vm.HomeModel.NGCount / (double)vm.HomeModel.ProduceCount * 100, 2);
                }
                if (ngPercent == 0)
                {
                    okPercent = 100;
                }
                PieCollection[0].Values = new ChartValues<double> { okPercent };
                PieCollection[1].Values = new ChartValues<double> { ngPercent };
            }

            vm.CurTime = DateTime.Now.ToString("yyyy/MM/dd  HH:mm:ss");
            vm.RunTime = ((DateTime.Now - startUpTime).TotalSeconds / (double)3600).ToString("f2");
            int count = logDg.Items.Count;

            if (count > 0)
            {
                var border = VisualTreeHelper.GetChild(logDg, 0) as Decorator;
                if (border != null)
                {
                    var scroll = border.Child as ScrollViewer;
                    if (scroll != null)
                    {
                        scroll.ScrollToEnd();//最后一行                        
                        logDg.SelectedIndex = count - 1;
                        //scroll.ScrollToHome();//第一行
                        //scroll.ScrollToLeftEnd();//第一列
                        //scroll.ScrollToRightEnd();//最后一列
                    }
                }
            }
            //心跳写入
            //DbHelper.LogTip("心跳写入");
            //mwvm.services.plc.Write($"DB{Fields.DbAddr}.DBX{Fields.Map["HeartBeat"].First}.0", true);

        }



     


        private void RecipeBtn_Click(object sender, RoutedEventArgs e)
        {
            Funcs.ShowUserControl("ProductSettingView");
        }

        /// <summary>
        /// 显示解绑按钮
        /// </summary>
        public static void RstCodeBtnShow()
        {
            RstCodeBtn.Visibility = Visibility.Visible;
            if (Fields.Station != "OP10" && Fields.Station != "OP50")
            {
                RstCodeBtn.SetValue(Grid.RowProperty, 4);
                RstCodeBtn.SetValue(Grid.ColumnProperty, 1);
            }
            else
            {
                RstCodeBtn.SetValue(Grid.RowProperty, 5);
                RstCodeBtn.SetValue(Grid.ColumnProperty, 1);

            }

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            string file = Paths.StationPicture;

            station.Text = Fields.Station;
            if (Fields.Station == "JZ")
            {
                station.Text = "减震装垫";


            }
            if (File.Exists(file))
            {
                picture.Source = new BitmapImage(new Uri(file));
            }
            else
            {
                //记录工位图片不存在
            }

            pipe.Series = PieCollection;
            //加载配方

        }

        private void ChangePic_Click(object sender, RoutedEventArgs e)
        {
            if (change.Content.ToString() == "SOP")
            {
                string mode = vm.HomeModel.ProduceModel.ToString();
                string[] files = Directory.GetFiles(Paths.SopDir);
                string matchFile = string.Empty;
                foreach (string file in files)
                {
                    if (Path.GetFileNameWithoutExtension(file) == mode)
                    {
                        matchFile = file;
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(matchFile))
                {
                    BitmapImage bitmap = new BitmapImage(new Uri(matchFile));
                    picture.Source = bitmap;
                    change.Content = "Back";
                }
                else
                {
                    MessageBox.Show("未找到匹配的SOP文件，请联系管理员进行配置！");
                }
            }
            else
            {
                change.Content = "SOP";
            }

        }

        /// <summary>
        /// 锁
        /// </summary>
        private object locker = new object();

        /// <summary>
        /// 复位按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RstBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {


               


                this.Dispatcher.Invoke(new Action(delegate
                {
                    int offset = Convert.ToInt32((sender as Button).CommandParameter);
                    //回原的时候并且手动
                    if (mwvm.plcData.SysBit[1] == true && offset == 3)
                    {
                        //重置采集数据
                        mwvm.ResetCollection();


                    }
                    //Log("复位开始");
                    Locator.Instance.Service.ResetButton(offset);
                    //Log("复位结束");
                }));

               
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        /// <summary>
        /// 置位按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
             
                this.Dispatcher.Invoke(new Action(delegate
                {
                    int offset = Convert.ToInt32((sender as Button).CommandParameter);
                    int val = Convert.ToInt32((sender as Button).Tag);
                    bool falg = val > 0 ? true : false;
                    Locator.Instance.Service.SettingButton(offset, falg);
                }));

            }
            catch (Exception ex)
            {

                throw;
            }

        }

        private void Test_Click(object sender, RoutedEventArgs e)
        {
           
               
                    var item = vm.PlcMsgs.Where(o => o.Index == 5 && o.MsgType == Enums.MsgType.Warning).FirstOrDefault();
                    if (item != null)
                    {
                        vm.PlcMsgs.Remove(item);
                    }
               
           

        }
        /// <summary>
        /// 强制NG
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ForceNG_Click(object sender, RoutedEventArgs e)
        {
            
                
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        //判断是否扫码，无扫码不能NG
                        if ((Fields.Station == "OP60" || Fields.Station == "GP12" || Fields.Station == "JZ") && vm.PartCodes.Count == 0)
                        {
                            MessageBox.Show("未扫总成码，不能强制NG！");
                            return;
                        }
                        int offset = Convert.ToInt32((sender as Button).CommandParameter);
                        bool falg = !(sender as ScriptBtn).IsChecked;
                        Locator.Instance.Service.ForceNGButton(offset, falg);
                    }));
                
           
        }


        /// <summary>
        /// 解绑页面弹出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RstCodeBtn_Click(object sender, RoutedEventArgs e)
        {
            Funcs.ShowUserControl("ResetPartCodeView");
        }



        /// <summary>
        /// 空托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EmptyTray_Click(object sender, RoutedEventArgs e)
        {
           
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        int offset = Convert.ToInt32((sender as Button).CommandParameter);
                        bool falg = !(sender as ScriptBtn).IsChecked;
                        Locator.Instance.Service.EmptyTrayButton(offset, falg);
                    }));
           
        }


        /// <summary>
        /// 消音屏蔽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mute_Click(object sender, RoutedEventArgs e)
        {
             
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        int offset = Convert.ToInt32((sender as Button).CommandParameter);
                        bool falg = !(sender as ScriptBtn).IsChecked;
                        //Log("消音开始");
                        Locator.Instance.Service.MuteButton(offset, falg);
                        //Log("消音结束");
                    }));
          
        }


        private static void Log(string message)
        {
            using (StreamWriter writer = new StreamWriter("D:/messge.txt", append: true))
            {
                string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
                writer.WriteLine(logMessage);
            }
        }

    }
}
